define([
    'text!planmanage/addfileplan/templates/AddFilePlan_second.html',
    'planmanage/addfileplan/views/AddFilePlan_variable'
], function(AddFilePlanSecondViewTpl, VariableView) {
    // 主机信息下拉树
    var srcHostIdTreeObj;
    // 主机配置gird
    var $srcHostGrid;
    // 源目录表达式配置gird
    var $sourceXpathGrid;
    
    return fish.View.extend({
        template: fish.compile(AddFilePlanSecondViewTpl),
        i18nData: fish.extend({}),
        events: {
            'click #buttonSrcFileAdd': 'buttonSrcFileAdd',
            'click #buttonSrcFileVerify': 'buttonSrcFileVerify'
        },

        initialize: function() {
            // 验证并获取源信息配置表单数据
            fish.on('getSrcFormData', $.proxy(this.getSrcFormData, this));
            // 源数据表单数据回绑
            fish.on('setSrcFileForm', $.proxy(this.setSrcFileForm, this));
        },

        serialize: function() {
            return this.i18nData;
        },

        //这里用来初始化页面上要用到的fish组件
        afterRender: function() {
            var me = this;
            // 源主机配置，下拉树
            var srcHostId_setting = {
                async: {
                    enable: true,
                    contentType: "application/json",
                    url: webRoot + 'baseconfig/dmfileplan/getHostInfo.do',
                    type: 'post'
                },
                view: {
                    dblClickExpand:false,
                    selectedMulti: false //如果为true,按住ctrl可以多选，false为单选 
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pId",
                        rootPId: 0
                    }
                },
                callback: {
                    onClick: srcHostIdonClick
                }
            };
            
            var srcHostIdTree = $.fn.zTree.init($("#srcHostId_tree"), srcHostId_setting);
            srcHostIdTreeObj = $.fn.zTree.getZTreeObj("srcHostId_tree");
            function srcHostIdonClick(){
                nodes = srcHostIdTree.getSelectedNodes();
                var nodeIdInput = $('input[name="srcHostId"]');
                nodeIdInput.val(nodes[0].name);
                me.addSrcHostGrid(nodes[0]);
                hidesrcHostIdTree();
            };
            //下拉树相对位置，随着窗口联动
            function srcHostIdTreePos(){
                var inputObj = $('input[name="srcHostId"]');
                var inputObjOffSet = $('input[name="srcHostId"]').offset();
                    var $treePs = $("#srcHostId_commbox_tree").css({left:inputObjOffSet.left + "px", top: inputObj.outerHeight() + "px",width:inputObj.outerWidth() + "px",'z-index':9999});
                    return $treePs;
                    }
            $('input[name="srcHostId"]').click(function(){
                srcHostIdTreePos().slideDown("fast");
                $(window).resize(function(){
                    srcHostIdTreePos();
                });
                $("body").bind("mousedown", onBodyDownNode);
            });
            function onBodyDownNode(event) {
                if (!(event.target.name == "srcHostId" || event.target.id == "srcHostId_commbox_tree" || $(event.target).parents("#srcHostId_commbox_tree").length>0)) {
                    hidesrcHostIdTree();
                }
            };
            function hidesrcHostIdTree(){
                $("#srcHostId_commbox_tree").fadeOut("fast");
                $("body").unbind("mousedown", onBodyDownNode);
            };

            // 源目录表达式配置
            $('input[name="sourceXpath"]').directory({
                dataTextField : "name",
                dataValueField : "value",
                addMenuWidth:120,
                value:[{type:'directory',value:'请配置目录：'}]
            });
        },
        addSrcHostGrid: function(addData){
            $('#srcHostGrid_div').removeClass("hidden");
            // 主机配置 显示gird
            $srcHostGrid = $("#srcHost_grid").grid({
                height: 110,
                colModel: [{
                    name: 'hostId',
                    label: '主机ID',
                    sortable: false,
                    hidden: true,
                    key: true
                }, {
                    name: 'busiSys',
                    label: '域分组',
                    align: 'center',
                    sortable: false
                }, {
                    name: 'ip',
                    label: '主机IP',
                    align: 'center',
                    sortable: false
                }, {
                    name: 'hostName',
                    label: '主机名称',
                    align: 'center',
                    sortable: false
                }, {
                    name: '',
                    formatter: 'actions',
                    classes: 'text-primary',
                    width: 30,
                    sortable: false,
                    formatoptions: {
                        editbutton: false, //默认开启编辑功能
                        delbutton: true //默认开启删除功能
                    }
                }],
                afterDeleteRow: function (e, rowid, data, option) {
                    var rowNum = $srcHostGrid.grid("getGridParam", "records");
                    if(rowNum == 0){
                        $('#srcHostGrid_div').addClass("hidden");
                        VariableView.setSrcHost_OK(false);
                        VariableView.setSourceXpath_OK(false);
                    }
                }
            });
            //获取所有的rowid记录
            var dataIds = $srcHostGrid.grid("getDataIDs");
            for(var i = 0; i < dataIds.length; i++){
                if(addData.hostId == dataIds[i]){
                    fish.toast('warn','该主机已经添加');
                    return;
                }
            }
            $srcHostGrid.grid("addRowData", addData);
            VariableView.setSrcHost_OK(true);
            VariableView.setSourceXpath_OK(false);
        },

        // 添加源目录表达式
        buttonSrcFileAdd: function(xpathStr){
            $('input[name="sourceXpath"]').directory('value');

            if(xpathStr.type == "click"){
                xpathStr = $('input[name="sourceXpath"]').val();
            }
            if($.parseJSON(xpathStr).length == 1){
                fish.toast('warn','请配置正确的源目录表达式');
                return;
            }
            $('#sourceXpathGrid_div').removeClass("hidden");
            // 主机配置 显示gird
            $sourceXpathGrid = $("#sourceXpath_grid").grid({
                height: 110,
                colModel: [{
                    name: 'xpathStr',
                    label: '源目录表达式预览',
                    sortable: false,
                    formatter:function(cellval, opts, rwdat, _act){
                        var result = '';
                        var value = $.parseJSON(cellval);
                        for(var i = 1; i < value.length; i++){
                            var btnName = '';
                            if(value[i].type == 'list'){
                                if(value[i].value == 1){
                                    btnName = "本地网";
                                }else if(value[i].value == 5){
                                    btnName = "客户分组";
                                }else if(value[i].value == 6){
                                    btnName = "清单序列";
                                }else if(value[i].value == 7){
                                    btnName = "进程号";
                                }
                            }else if(value[i].type == 'timer'){
                                var btnValues = value[i].value.split(",");
                                if(btnValues[0] == '3'){// 年月日
                                    btnName = "时间变量：偏移"+btnValues[1]+"-"+btnValues[2]+"天";
                                }else if(btnValues[0] == '2'){// 年月
                                    btnName = "时间变量：偏移"+btnValues[1]+"-"+btnValues[2]+"个月";
                                }else if(btnValues[0] == '33'){// 年-月-日
                                    btnName = "时间变量：偏移"+btnValues[1]+"-"+btnValues[2]+"天";
                                }else if(btnValues[0] == '22'){// 年-月
                                    btnName = "时间变量：偏移"+btnValues[1]+"-"+btnValues[2]+"个月";
                                }else{
                                    btnName = "时间变量";
                                }
                            }else if(value[i].type == '4'){
                                var btnValues = value[i].value.split(",");
                                btnName = "账期";
                                if(btnValues[0] != '账期'){
                                    btnName = "账期：偏移"+btnValues[0]+"-"+btnValues[1]+"个月";
                                }
                            }else{
                                btnName = value[i].value;
                            }
                            result += '<button type="button" class="btn btn-default ui-filenamegrid-btn">'+btnName+'</button>';
                        }
                        return result;
                    }
                }, {
                    name: '',
                    formatter: 'actions',
                    classes: 'text-primary',
                    width: 10,
                    sortable: false,
                    formatoptions: {
                        editbutton: false, //默认开启编辑功能
                        delbutton: true //默认开启删除功能
                    }
                }],
                afterDeleteRow: function (e, rowid, data, option) {
                    var rowNum = $sourceXpathGrid.grid("getGridParam", "records");
                    if(rowNum == 0){
                        $('#sourceXpathGrid_div').addClass("hidden");
                    }
                    VariableView.setSourceXpath_OK(false);
                }
            });

            var newData = {"xpathStr": xpathStr};
            $sourceXpathGrid.grid("addRowData", newData);

            VariableView.setSourceXpath_OK(false);
        },

        // 源目录表达式验证 按钮点击事件
        buttonSrcFileVerify: function(){
            if(!$sourceXpathGrid || $sourceXpathGrid.grid("getRowData").length == 0){                
                $('textarea[name="sourceXpath_show"]').val('');
                fish.toast('warn','请配置源目录表达式');
            }else{
                var sourceXpathGridData = $sourceXpathGrid.grid("getRowData");
                var data = VariableView.getPlanFormData();
                data.sourceXpathGridDataStr = this.getGridDataStr(2, $sourceXpathGrid.grid("getRowData"));
                fish.ajax({
                    async : false,
                    url: ctx + '/baseconfig/dmfileplan/xpathVerify.do',
                    showMask: false,  //是否自动显式全局遮罩
                    showError: true, //在出现异常时自动显示异常信息，后台需要返回的数据格式：{code:'ERROR-1001',message:'登录失败'}
                    timeout: 30000,   //超过3秒显式全局遮罩，此参数在showMask为true时才有效
                    data: data,
                    beforeSend: function(){
                        $.blockUI({message : "源目录表达式验证中,请稍候..."});
                    },
                    complete: function(xhr, status){
                        $.unblockUI();
                        if(status == 'timeout'){
                            fish.toast('error', "网络请求超时");
                            return;
                        }
                        $('textarea[name="sourceXpath_show"]').val('');
                        var xpath = "";
                        var xpathList = xhr.responseJSON.xpathList;
                        for(var i = 0; i < xpathList.length; i++){
                            xpath += xpathList[i]+"\n";
                        }
                        if(xhr.responseJSON.xpathIsOK){// 验证通过
                            VariableView.setSourceXpath_OK(true);
                        }else{
                            xpath = "ERROR:\n" + xpath;
                            VariableView.setSourceXpath_OK(false);
                        }
                        $('textarea[name="sourceXpath_show"]').val(xpath);
                    },
                    //【注意】如果你在这里配置了自己的error处理函数，fish.ajax就不会自动帮你显示异常信息了！
                    error:function(){
                        $.unblockUI();
                    }
                });
            }
        },

        // 获取源数据配置表单数据
        getSrcFormData: function(){
            var srcFileFormData = $("#srcFileForm").form("value");
            // 判断有没有选择源主机
            if(!$srcHostGrid || !VariableView.getSrcHost_OK()){
                fish.toast('warn','请选择源主机');
                VariableView.setSrcHost_OK(false);
                VariableView.setSrcFileForm_OK(false);
            }else{
                // 判断源目录表达式配置预览是否成功
                if(!VariableView.getSourceXpath_OK()){
                    fish.toast('warn','源目录表达式配置未验证或验证不通过，请点击“结果预览”按钮进行验证');
                    VariableView.setSrcFileForm_OK(false);
                }else{
                    srcFileFormData.srcHostGridDataStr = this.getGridDataStr(1, $srcHostGrid.grid("getRowData"));
                    // 判断有没有配置源目录表达式
                    if(!$sourceXpathGrid){
                        fish.toast('warn','请配置源目录表达式');
                        VariableView.setSrcFileForm_OK(false);
                    }else{
                        srcFileFormData.sourceXpathGridDataStr = this.getGridDataStr(2, $sourceXpathGrid.grid("getRowData"));
                        VariableView.setSrcFileFormData(srcFileFormData);
                        VariableView.setSrcFileForm_OK(true);
                    }
                }
            }
        },

        // 获取有用的gridData，并转成String
        getGridDataStr: function(type, gridData){
            var newGridData = [];
            for(var i = 0; i < gridData.length; i++){
                var oneData = {};
                if(type == 1){
                    oneData.hostId = gridData[i].hostId;
                    oneData.ip = gridData[i].ip;
                }else if(type == 2){
                    oneData.xpathStr = gridData[i].xpathStr;
                }
                newGridData.push(oneData);
            }
            return JSON.stringify(newGridData);
        },

        // 源数据表单数据回绑
        setSrcFileForm: function(){
            $.blockUI({message : "加载源数据中,请稍候..."});
            var data = VariableView.getDmStrategyInfo();
            // 并发数
            $("input[name='concurrentNumber']").val(data.concurrentNumber);
            // 源主机
            var srcHostGridData = $.parseJSON(data.srcHostGridDataStr);
            for(var i = 0; i < srcHostGridData.length; i++){
                this.addSrcHostGrid(srcHostGridData[i]);
            }
            // 源目录表达式
            for(var i = 0; i < data.sourceXpathGridData.length; i++){
                this.buttonSrcFileAdd(data.sourceXpathGridData[i].xpathStr);
            }
            VariableView.setSourceXpath_OK(true);
            VariableView.setSourceDataId(data.sourceDataId);
            $.unblockUI();
        }
    });
});